<?php
namespace app\Logic\Layui\Service;

use app\Logic\Logic;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use app\Logic\Layui\ServiceProviders\VerificationCode;
use Illuminate\Support\Facades\Session;

class ImageCode extends Logic implements ServiceInterface
{
    public $app;

    public function __construct(VerificationCode $app)
    {
        $this->app = $app;
    }


    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function image()
    {
        $phrase = new PhraseBuilder;
        $code = $phrase->build(4);
        $builder = new CaptchaBuilder($code, $phrase);
        $builder->setBackgroundColor(218, 235, 242);
        $builder->setMaxAngle(0);
        $builder->setMaxBehindLines(0);
        $builder->setMaxFrontLines(0);
        $builder->setTextColor(50, 34, 168);
        $builder->build($width = 150, $height = 40, $font = null);
        $phrase = $builder->getPhrase();

        $time = date('Y-m-d');
        $filePath = public_path() . DS . '../public/code/' .$time . '/';
        if (!is_dir($filePath)) {
            mkdir($filePath, 0777 , true);
            chmod($filePath, 0777);
        }

        $filename = md5(microtime(true)).'.jpg';
        $builder->save($filePath . $filename);

        session(['imgCode'=>$phrase]);

        return $this->success(['path'=>'/code/' . $time . '/' . $filename]);
    }

}